package com.suma.platform.core.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.nfsq.platform.utils.bean.ResultBean;
import com.suma.platform.core.exception.SumaException;

/**
 * @author suma
 * @date 2018/1/10 下午4:52
 */
@Aspect
@Order(0)
@Component
public class ControllerAop {

	private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);

	public ControllerAop() {
		logger.debug("开始初始化自定义控制器aop...");
	}

	@Around("execution(* com.suma.platform.core.controller..*.*(..))")
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();

		ResultBean<?> result;

		try {
			result = (ResultBean<?>) pjp.proceed();
			logger.info("{} use time: {} ms", pjp.getSignature(), (System.currentTimeMillis() - startTime));
		} catch (Throwable e) {
			result = handlerException(pjp, e);
		}
		return result;
	}

	private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		ResultBean<?> result;

		// 已知异常
		if (e instanceof SumaException) {
			result = new ResultBean(e);
		} else {
			logger.error(pjp.getSignature() + " error ", e);
			// TODO 未知的异常，应该格外注意，可以发送邮件通知等
			result = new ResultBean(e);
		}
		return result;
	}

}
